<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const activeIndex = ref('1')
const router = useRouter()

// 检查用户是否登录
const user = ref(null)
onMounted(() => {
  const storedUser = localStorage.getItem('user')
  if (storedUser) {
    user.value = JSON.parse(storedUser)
  }
})

const logout = () => {
  localStorage.removeItem('user')
  user.value = null
  router.push('/')
}
</script>

<template>
  <el-menu class="el-menu-demo" mode="horizontal" :ellipsis="false" @select="handleSelect">
    <el-menu-item>
      <router-link to="/">
        <img style="width: 3.2rem" src="../assets/LOGO.png" alt="Element logo" />
      </router-link>
    </el-menu-item>

    <!-- 如果未登录 -->
    <template v-if="!user">
      <el-menu-item style="border-radius: 20px;">
        <router-link to="/login" class="nav-link">登录</router-link>
      </el-menu-item>
      <el-menu-item style="border-radius: 20px;">
        <router-link to="/register" class="nav-link">注册</router-link>
      </el-menu-item>
    </template>

    <!-- 如果已登录 -->
    <template v-else>
      <el-sub-menu index="avatar-menu">
        <template #title>
          <div>头像占位</div>
<!--          <img-->
<!--              :src="user.avatar || 'https://i.pravatar.cc/40?img=3'"-->
<!--              alt="头像"-->
<!--              style="width: 30px; height: 30px; border-radius: 50%; object-fit: cover"-->
<!--          />-->
        </template>
        <el-menu-item @click="router.push('/')">个人中心</el-menu-item>
        <el-menu-item @click="logout">退出登录</el-menu-item>
      </el-sub-menu>
    </template>
  </el-menu>
</template>

<style scoped>
.el-menu-demo {
  padding: 0 20px;
  background-color:rgb(232.8, 233.4, 234.6);
}

.el-menu--horizontal > .el-menu-item:nth-child(1) {
  margin-right: auto;
}

.nav-link {
  text-decoration: none;
  color: inherit;
  padding: 8px 16px;
  transition: all 0.3s ease;
}

.el-menu--horizontal > .el-menu-item:first-child:hover {
  background-color: transparent !important;
  cursor: default;
}
</style>
